<template>
  <div class="p-2">
    <div class="search" v-show="showSearch">
      <a-form ref="queryFormRef" :model="queryParams" layout="inline">
        <a-form-item label="表单名称" name="formName">
          <a-input v-model:value="queryParams.formName" placeholder="请输入表单名称" allow-clear @pressEnter="handleQuery" />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleQuery">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="resetQuery">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>

    <a-card :bordered="false">
      <template #title>
        <a-space>
          <a-button type="primary" @click="handleAdd">
            <template #icon><PlusOutlined /></template>
            新增
          </a-button>

          <a-button type="primary" :disabled="single" @click="handleUpdate()">
            <template #icon><EditOutlined /></template>
            修改
          </a-button>

          <a-button type="primary" danger :disabled="multiple" @click="handleDelete()">
            <template #icon><DeleteOutlined /></template>
            删除
          </a-button>

          <a-button @click="handleExport" v-hasPermi="['workflow:form:export']">
            <template #icon><DownloadOutlined /></template>
            导出
          </a-button>
        </a-space>
      </template>

      <a-table
        :loading="loading"
        :columns="columns"
        :data-source="formList"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: handleSelectionChange }"
        :pagination="{
          total,
          current: queryParams.pageNum,
          pageSize: queryParams.pageSize,
          onChange: handleTableChange,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
        }"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'api'">
            <div v-for="(value, key) in record.api" :key="key">{{ apiTypeNames[key] }}: {{ value }}</div>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-tooltip title="修改">
                <a-button type="link" @click="handleUpdate(record)" v-hasPermi="['workflow:form:edit']">
                  <template #icon><EditOutlined /></template>
                </a-button>
              </a-tooltip>
              <a-tooltip title="删除">
                <a-button type="link" @click="handleDelete(record)" v-hasPermi="['workflow:form:remove']">
                  <template #icon><DeleteOutlined /></template>
                </a-button>
              </a-tooltip>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-modal
      :title="addFormVisible.title"
      v-model:open="addFormVisible.visible"
      @ok="submitForm"
      @cancel="cancel"
      width="800px"
      :keyboard="true"
      :maskClosable="false"
      :destroyOnClose="true"
    >
      <a-form ref="formFormRef" :model="form" :rules="rules" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" autocomplete="off">
        <a-form-item label="表单名称" name="formName">
          <a-input v-model:value="form.formName" placeholder="请输入表单名称" :autoFocus="true" />
        </a-form-item>

        <a-form-item label="组件路径" name="componentPath">
          <a-input v-model:value="form.componentPath" placeholder="请输入组件路径 /@/views/xxxx.vue" />
        </a-form-item>

        <a-form-item label="service全路径" name="servicePath">
          <a-input v-model:value="form.servicePath" placeholder="请输入service全路径 xxx.xxx.service" />
        </a-form-item>

        <a-form-item label="绑定流程" name="processKey">
          <a-select
            v-model:value="form.processKey"
            style="width: 100%"
            placeholder="请选择流程"
            :options="
              processList?.map((item) => ({
                value: item.processKey,
                label: item.processName,
              }))
            "
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup name="Form">
  import { formApi } from '/@/api/workflow/form';
  import { deployApi } from '/@/api/workflow/deploy';
  import { message, Modal } from 'ant-design-vue';

  const { proxy } = getCurrentInstance();

  const formList = ref([]);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const selectedRowKeys = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);

  const columns = [
    {
      title: '表单名称',
      dataIndex: 'formName',
      key: 'formName',
    },
    {
      title: '关联流程key',
      dataIndex: 'processKey',
      key: 'processKey',
    },
    {
      title: '前端组件路径',
      dataIndex: 'componentPath',
      key: 'componentPath',
    },
    {
      title: '后端service全路径',
      dataIndex: 'servicePath',
      key: 'servicePath',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      align: 'center',
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 180,
      fixed: 'right',
    },
  ];

  const vfDesignerRef = ref(null);
  const vfRenderRef = ref(null);
  const formFormRef = ref();
  const queryFormRef = ref();

  const designerConfig = reactive({
    externalLink: true,
    toolbarMaxWidth: 510,
    // languageMenu: true,
    //externalLink: false,
    //formTemplates: false,
    //eventCollapse: false,
    //clearDesignerButton: false,
    //previewFormButton: false,
  });
  const addFormVisible = reactive({
    visible: false,
    title: '',
  });
  const render = reactive({
    visible: false,
    title: '',
  });
  const dialog = reactive({
    visible: false,
    title: '',
  });
  const apiTypeNames = {
    addApi: '新增接口',
    submitApi: '提交接口',
    updateApi: '更新接口',
    detailApi: '详情接口',
  };
  const initFormData = {
    formId: undefined,
    formName: '',
    processKey: undefined,
    componentPath: '',
    servicePath: '',
    remark: '',
  };
  const data = reactive({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      formName: '',
    },
    rules: {
      formName: [{ required: true, message: '表单名称不能为空', trigger: 'blur' }],
      processKey: [{ required: true, message: '请选择流程', trigger: 'blur' }],
      componentPath: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
      servicePath: [{ required: true, message: '请输入service全路径', trigger: 'blur' }],
    },
  });

  const { queryParams, form, rules } = toRefs(data);

  const getList = async () => {
    loading.value = true;
    const { data } = await formApi.listForm(queryParams.value);
    formList.value = data.list;
    total.value = data.total;
    loading.value = false;
  };
  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  };
  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
  };
  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  };
  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value.resetFields();
    handleQuery();
  };

  const handleTableChange = (page, pageSize) => {
    queryParams.value.pageNum = page;
    queryParams.value.pageSize = pageSize;
    getList();
  };

  const handleSelectionChange = (keys, rows) => {
    selectedRowKeys.value = keys;
    ids.value = rows.map((item) => item.formId);
    single.value = keys.length !== 1;
    multiple.value = !keys.length;
  };

  const processList = ref([]);
  const getModalData = async () => {
    let { data } = await deployApi.listDeploy({ pageNum: 1, pageSize: 9999 });
    processList.value = data.list;
  };

  /** 新增表单操作 */
  const handleAdd = () => {
    nextTick(() => {
      getModalData();
      addFormVisible.title = '新增表单';
    });
    addFormVisible.visible = true;
  };
  /** 修改表单操作 */
  const handleUpdate = (row) => {
    addFormVisible.visible = true;
    nextTick(async () => {
      const formId = row?.formId || ids.value[0];
      const res = await formApi.getForm(formId);
      form.value = res.data;
    });
  };
  /** 查看表单操作 */
  const handleDetail = (row) => {
    render.visible = true;
    render.title = '查看表单详情';
    nextTick(async () => {
      vfRenderRef.value.setFormJson(row.content || { formConfig: {}, widgetList: [] });
    });
  };
  /** 提交表单操作 */
  const submitForm = () => {
    nextTick(async () => {
      form.value.formId ? await formApi.updateForm(form.value) : await formApi.addForm(form.value);
      message.success('操作成功');
      dialog.visible = false;
      addFormVisible.visible = false;
      getList();
    });
  };
  /** 删除按钮操作 */
  const handleDelete = async (row) => {
    const formIds = row?.formId || ids.value;
    try {
      await Modal.confirm({
        title: '确认删除',
        content: '是否确认删除表单编号为"' + formIds + '"的数据项？',
        okText: '确认',
        cancelText: '取消',
      });
      await formApi.delForm(formIds);
      getList();
      message.success('删除成功');
    } catch (error) {
      // 用户取消删除操作
    }
  };
  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download(
      'workflow/form/export',
      {
        ...queryParams.value,
      },
      `form_${new Date().getTime()}.xlsx`
    );
  };

  onMounted(() => {
    getList();
  });
</script>

<style lang="less" scoped>
  .search {
    margin-bottom: 16px;
  }
</style>
